﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace PersonaLibrary.CustomProperties
{
    [XmlRoot("dictionary")]
    public class SerializableDictionary : Dictionary<string, PropertiesItem>, IXmlSerializable
    {
        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(string));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(PropertiesItem));
            
            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();
            
            if (wasEmpty)
                return;
            
            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                reader.ReadStartElement("item");
                
                reader.ReadStartElement("key");
                string key = (string)keySerializer.Deserialize(reader);
                reader.ReadEndElement();
                
                reader.ReadStartElement("value");
                PropertiesItem value = (PropertiesItem)valueSerializer.Deserialize(reader);
                reader.ReadEndElement();
                
                this.Add(key, value);
                
                reader.ReadEndElement();
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }
        
        public void WriteXml(System.Xml.XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(string));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(PropertiesItem));
            foreach (string key in this.Keys)
            {
                writer.WriteStartElement("item");
                writer.WriteStartElement("key");
                keySerializer.Serialize(writer, key);
                writer.WriteEndElement();

                writer.WriteStartElement("value");
                PropertiesItem value = this[key];
                valueSerializer.Serialize(writer, value);
                writer.WriteEndElement();

                writer.WriteEndElement();
            }
        }

        public new PropertiesItem this[string key]
        {
            get
            {
                if (base.Keys.Contains(key)) return base[key];
                else
                {
                    PropertiesItem item = new PropertiesItem();
                    item.SetDefault();
                    base[key] = item;
                    return item;
                }
            }
            set
            {
                base[key] = value;
            }
        }

        #endregion
    }
}
